//
//  LLActionManager.swift
//  LiLi
//
//  Created by liuzhu on 2019/1/9.
//  Copyright © 2019 liuzhu. All rights reserved.
//

import UIKit

class LLActionManager: NSObject {
    //初始化
    static let actionManager:LLActionManager = {
        let a = LLActionManager()
        return a
    }()
    
    //获取单例
    class func shareActionManager()->LLActionManager{
        return actionManager
    }
    
    func deleteAction(action:LLAction,finish:@escaping(_ isSuccess:Bool)->()){
        //删除action，
        DataManager.deleteAction(recordName: action.recordName!) { (isSuccess) in
            if isSuccess{
                finish(true)
                LLNotificationManager.shareNotificationManager().deleteNotification(action: action, finish: { (action, isSuccess, message) in
                    
                })
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionDeleteKey), object: nil, userInfo: ["action":action])
            }else{
                finish(false)
            }
        }
    }
    
    func queryAction(actionId:String,finish:@escaping(_ model:LLAction?,_ isSuccess:Bool)->()){
        //查找action
        let action = DataManager.QueryAction(recordName: actionId)
        if action != nil{
            finish(action!,true)
        }else{
            finish(nil,false)
        }
    }
    
    func queryActions(finish:@escaping(_ model:[LLAction]?,_ isSuccess:Bool)->()){
        DataManager.QueryActions { (actions, isSuccess) in
            if isSuccess{
                finish(actions,isSuccess)
            }else{
                finish(nil,false)
            }
        }
    }
    
    func queryActionsWithDateStr(dateStr:String,finish:@escaping(_ model:[LLAction]?,_ isSuccess:Bool)->()){
        DataManager.QueryActionsWithDateStr(dateStr: dateStr) { (actions, isSuccess) in
            if isSuccess{
                finish(actions,isSuccess)
            }else{
                finish(nil,false)
            }
        }
    }
    
    
    /// 创建一个日程
    ///
    /// - Parameters:
    ///   - actionType: 日程类型 个人，公司，其他
    ///   - repeatTag: 提醒标志：一次，每日，每周，每月，每天
    ///   - titleName: 日程标题
    ///   - dateStr: 第一次提醒的日期
    ///   - timeStr: 提醒时间
    ///   - finish: <#finish description#>
    func createAction(actionType:ActionType,repeatTag:ActionRepeatTag,titleName:String,des:String,dateStr:String,timeStr:String,finish:@escaping(_ action:LLAction?,_ isSuccess:Bool,_ message:String)->()){
        if isExceedMaxCount() {
            finish(nil,false,"未完成的日程超过50个最大限制了,请先删除几个")
            return
        }
        let randNum = String(format: "%d", arc4random() % 100000)
        let action = LLAction()
        action.recordName = "\(dateStr)-\(timeStr)-\(randNum)"
        action.dateStr = dateStr
        let subDateStrList = LLDateUtil.shareLLDateUtil().getDayStrListAfterTheDay(dateStr: dateStr, repeatTag: repeatTag)
        if subDateStrList != nil && subDateStrList?.count != 0{
            var subDateStr = ""
            for str in subDateStrList!{
                subDateStr = subDateStr + "\(str)" + ","
            }
            action.subDateStr = subDateStr
        }
        action.timeStr = timeStr
        action.titleName = titleName
        action.actionType = actionType
        action.repeatTag = repeatTag
        action.des = (des.count != 0) ? des : titleName
        action.needTip = 1
        action.refreshTag = 0
        action.status = 0
        action.createTime = "\(LLDateUtil.shareLLDateUtil().getCurrentDate().timeIntervalSince1970)"
        action.updateTime = "\(LLDateUtil.shareLLDateUtil().getCurrentDate().timeIntervalSince1970)"
        DataManager.saveAction(action: action) { (isSuccess) in
            if isSuccess{
                //播放通知，又一个新的action被创建了，请和自己相关的类执行必要的操作
                //NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionAddKey), object: nil, userInfo: ["action":action])
                finish(action,true,"创建日程成功")
            }else{
                finish(nil,false,"创建日程失败")
            }
        }
    }
    
    /// 判断Action数量是否已经达到最大限度
    ///
    /// - Returns: true:达到最大限度，无法再增加，false:未达到最大限度，还可以继续增加
    func isExceedMaxCount() -> Bool{
        var isExceed = false
        let count = DataManager.getActionCount()
        if count >= LLConst.maxActionCountLimit(){
            isExceed = true
        }
        return isExceed
    }
    
    func isHaveActionInTheDateStr(dateStr:String) -> [LLAction]? {
        let actions = DataManager.LikeActions(dateStr: dateStr)
        if actions != nil{
            return actions!
        }else{
            return nil
        }
    }
    
    //析构
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
